package com.czk.register;

import com.czk.framework.URL;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/4/14 17:01
 */
public class RemoteRegister {
    /**
     * 私有变量
     * 两种进程会加载不同的map进入内存，不进行内存共享
     * 所以一般选择zookeeper第三方进行注册
     */
    private static Map<String, List<URL>> map = new ConcurrentHashMap<>(16);

    /**
     * 注册
     *
     * @param interfaceName
     * @param url
     */
    public static void register(String interfaceName, URL url) throws IOException {
        // 拿到集合
        List<URL> urls = map.get(interfaceName);
        // 是否为空
        if (urls == null) {
            // 创建集合
            urls = new ArrayList<>(10);
        }
        urls.add(url);
        // 注册
        map.put(interfaceName, urls);
        saveFile();
    }

    /**
     * 拿到地址
     *
     * @param interfaceName
     * @return
     */
    public static URL random(String interfaceName) {
        map = getFile();
        // 拿到
        List<URL> urls = map.get(interfaceName);
        // 拿到长度
        int length = urls.size();
        // 拿到随机数
        int i = new Random().nextInt(length);
        return urls.get(i);
    }

    public static void saveFile() throws IOException {
        FileOutputStream fileOutputStream = new FileOutputStream("/temp.txt");
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
        objectOutputStream.writeObject(map);
    }

    /**
     * 解决不同进程之间的文件共享问题
     *
     * @return
     */
    public static Map<String, List<URL>> getFile() {
        try {
            FileInputStream fileInputStream = new FileInputStream("/temp.txt");
            ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
            return (Map<String, List<URL>>) objectInputStream.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}
